package config_center

import (
	"context"
	"fmt"
	"payme3000/framework/errorx"
	"strconv"
	"sync"
)

// AtomicInt64 int64类型的配置值
type AtomicInt64 struct {
	sync.RWMutex
	value    int64
	strValue string
}

func NewAtomicInt64(val int64) *AtomicInt64 {
	return &AtomicInt64{
		value:    val,
		strValue: fmt.Sprintf("%d", val),
	}
}

func (a *AtomicInt64) Store(newStrValue string) bool {
	a.Lock()
	defer a.Unlock()

	if a.strValue == newStrValue {
		return false
	}

	newValue, err := strconv.ParseInt(newStrValue, 10, 64)
	if err != nil {
		errorx.Catch(context.Background(), err)
		return false
	}

	a.strValue = newStrValue
	a.value = newValue

	return true
}

func (a *AtomicInt64) String() string {
	a.RLock()
	defer a.RUnlock()

	return a.strValue
}

func (a *AtomicInt64) Int64() int64 {
	a.RLock()
	defer a.RUnlock()

	return a.value
}
